package com.cbh.amadeus.server.utils;

import com.cbh.amadeus.common.protocol.AmadeusMessageWrap;
import com.cbh.amadeus.server.domain.DelayAmadeusMessageWrap;
import com.cbh.amadeus.server.handler.PublishHandler;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.DelayQueue;

/**
 * @author ChenBiHui
 * @date 2025/5/17
 */
@Slf4j
public class MessageApproachManage {

    private static final DelayQueue<DelayAmadeusMessageWrap> DELAY_QUEUE_WITH_AMADEUS = new DelayQueue<>();

    public static void start() {
        Thread delay = new Thread(() -> {
            while (true) {
                try {
                    DelayAmadeusMessageWrap take = DELAY_QUEUE_WITH_AMADEUS.take();
                    PublishHandler.publish(take.getClient(), take.getWrap());
                } catch (Throwable e) {
                    log.error(e.getMessage(), e);
                }
            }
        });
        delay.setName("amadeus-message-delay");
        delay.setDaemon(true);
        delay.start();
        log.info("===== AmadeusMessageDelay started =====");
    }

    public static void push(Channel client, AmadeusMessageWrap wrap) {
        DELAY_QUEUE_WITH_AMADEUS.offer(new DelayAmadeusMessageWrap(client, wrap));
    }
}
